package com.haiyi.software.app;

import java.io.File;

import org.apache.http.Header;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.haiyi.software.app.basic.ActivityBasicSplash;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.service.HIChatServices;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

public class ActivitySplash extends ActivityBasicSplash {

	private Handler mHandler;

	private TextView textView_version, textView_down;

	private ProgressBar progressBar_down;

	private RelativeLayout RelativeLayout_down;

	@Override
	protected void onResume() {
		// TODO 自动生成的方法存根
		super.onResume();
		// testUrl();
		ckVersion();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		initComp();
		initData();
		initScreenWidth();
	}

	private void initScreenWidth() {

		DisplayMetrics metric = new DisplayMetrics();

		getWindowManager().getDefaultDisplay().getMetrics(metric);

		int screenWidth = metric.widthPixels; // 屏幕宽度（像素）

		MainApplication.getInstance().setScreenWidth(screenWidth);

	}

	private void initData() {

		this.textView_version.setText(MainApplication.VERSION);

	}

	private void initComp() {
		this.textView_version = (TextView) this
				.findViewById(R.id.textView_version);

		this.progressBar_down = (ProgressBar) this
				.findViewById(R.id.progressBar_down);

		this.textView_down = (TextView) this.findViewById(R.id.textView_down);

		this.RelativeLayout_down = (RelativeLayout) this
				.findViewById(R.id.RelativeLayout_down);
	}

	Runnable gotoLoginAct = new Runnable() {

		@Override
		public void run() {
			startActivity(new Intent(ActivitySplash.this, LoginActivity.class));
			finish();
		}
	};

	@Override
	protected void StartApp() {

		if (!MyTools.getInstance().isServiceRunning(this,
				"com.haiyi.software.xmpp.service.HIChatServices")) {

			L.i("服务不存在");

			Intent intent = new Intent(this, HIChatServices.class);

			startService(intent);
		} else {
			L.i("服务存在！！！！");
		}
		mHandler = new Handler();

		mHandler.postDelayed(gotoLoginAct, 500);
	}

	@Override
	protected void requestError() {

		Toast.makeText(this, "没有可连接网络", Toast.LENGTH_LONG).show();
	}

	@Override
	protected void requestFinish(JsonObject jsonObject_return) {

		int i = jsonObject_return.get("status").getAsInt();

		L.i("state=" + i);

		switch (i) {

		case 200:
			getAddress();
			break;
		case 201:

			int mustUpdate = jsonObject_return.getAsJsonObject("body")
					.get("mustUpdate").getAsInt();

			if (mustUpdate == 1) {

				Builder builder = new AlertDialog.Builder(ActivitySplash.this);

				builder.setTitle("软件版本更新")
						.setMessage(jsonObject_return.get("desc").getAsString())
						.setPositiveButton("下载", okClick).show();

			} else {

				Builder builder = new AlertDialog.Builder(ActivitySplash.this);

				builder.setTitle("软件版本更新")
						.setMessage(jsonObject_return.get("desc").getAsString())
						.setPositiveButton("下载", okClick)
						.setNegativeButton("下次再说", cancelClick).show();

			}

			break;
		case 202:
			Toast.makeText(this, jsonObject_return.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();
			break;
		case 203:
			Toast.makeText(this, jsonObject_return.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();
			break;
		}
	}

	private DialogInterface.OnClickListener okClick = new DialogInterface.OnClickListener() {

		String fsrc;

		@Override
		public void onClick(DialogInterface dialog, int which) {

			fsrc = MainApplication.getInstance().getAppApkDirectory()
					+ "/HIChat.apk";

			String apk = MainApplication.getInstance().getResources()
					.getString(R.string.apkurl);

			File file = new File(fsrc);

			AsyncHttpClient client = MainApplication.getInstance()
					.getAsyncHttpClient();

			client.post(apk, new FileAsyncHttpResponseHandler(file) {

				public void onStart() {

					RelativeLayout_down.setVisibility(View.VISIBLE);
				};

				public void onProgress(int bytesWritten, int totalSize) {

					textView_down.setText(bytesWritten + "/" + totalSize);
					progressBar_down.setMax(totalSize);
					progressBar_down.setProgress(bytesWritten);
				};

				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, File file) {

				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						File file) {
					RelativeLayout_down.setVisibility(View.GONE);

					installApk(fsrc);
				}
			});

		}
	};

	private void installApk(String filename) {
		File file = new File(filename);
		if (file.exists()) {
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setAction(Intent.ACTION_VIEW);
			String type = "application/vnd.android.package-archive";
			intent.setDataAndType(Uri.fromFile(file), type);
			startActivity(intent);
		} else {
			Toast.makeText(this, "安装文件不存在", Toast.LENGTH_LONG).show();
		}

	}

	private DialogInterface.OnClickListener cancelClick = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

			getAddress();

		}
	};
}
